<template>
  <div class="search-by-image">
    <a-modal v-model:open="visible" title="图片搜索" :footer="null" style="text-align: center">
      <a-typography-title :level="4">选择以下任意一种方式开始你的搜索</a-typography-title>
      <a-input-search
        v-model:value="searchUrl"
        placeholder="请在此处粘贴图片网址"
        enter-button
        @search="onSearch"
      />

      <!--      上传图片-->
      <a-upload
        v-model:file-list="fileList"
        name="avatar"
        list-type="picture-card"
        :show-upload-list="false"
        :before-upload="beforeUpload"
        :custom-request="handleUpload"
        style="height: 40vh"
      >
        <div>
          <loading-outlined v-if="loading"></loading-outlined>
          <plus-outlined style="font-size: 4em" v-else></plus-outlined>
          <div class="ant-upload-text">拖拽或粘贴上传图片</div>
        </div>
      </a-upload>

      <a-typography-paragraph style="margin-top: 3vh">
        请选择png，jpg格式图片，不超过10MB
      </a-typography-paragraph>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { message, type UploadProps } from 'ant-design-vue'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { savePictureUsingPost } from '@/api/pictureController.ts'
import { useRouter } from 'vue-router'

const router = useRouter()
const visible = defineModel()

const searchUrl = ref<string>('')
const onSearch = () => {
  if (!searchUrl.value) {
    message.error('请输入图片URL')
    return
  }
  router.push({
    path: '/picture/search/similar',
    query: {
      url: searchUrl.value,
    }
  })
}

const fileList = ref([])
const loading = ref<boolean>(false)

const handleUpload = async ({ file }: any) => {
  loading.value = true
  const res = await savePictureUsingPost({}, {}, file)
  if(res.data.code === 0 && res.data.data) {
    console.log(res.data.data)
    searchUrl.value = res.data.data?.url
    router.push({
      path: '/picture/search/similar',
      query: {
        url: searchUrl.value,
      }
    })
  }
  loading.value = false
}

const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传格式为jpeg，和png')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不超过2MB')
  }
  return isJpgOrPng && isLt2M
}
</script>

<style scoped lang="scss">
:deep(.ant-upload-select-picture-card) {
  margin: 10px !important;
  width: 100% !important;
  height: 40vh !important;
}
</style>
